﻿using FirstDemo.Common;
using FirstDemo.Log4net;
using FirstDemo.Models;
using Microsoft.AspNetCore.Http;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace FirstDemo.Middleware
{
    public class ResponseTimeMiddleware
    {
        // Name of the Response Header, Custom Headers starts with "X-"  
        private const string RESPONSE_HEADER_RESPONSE_TIME = "X-Response-Time-ms";
        // Handle to the next Middleware in the pipeline  
        private readonly RequestDelegate _next;
        public ResponseTimeMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public Task InvokeAsync(HttpContext context)
        {
            var watch = new Stopwatch();
            watch.Start();
            context.Response.OnStarting(() =>
            {
                watch.Stop();
                var responseTimeForCompleteRequest = watch.ElapsedMilliseconds;

                //log4net测试
                var ip = context.Connection.RemoteIpAddress.MapToIPv4().ToString();
                var userAgent = context.Request.Headers["User-Agent"].ToString();
                string browserName, ver;
                Utils.GetBrowserName(userAgent, out browserName, out ver);

                if (Regex.IsMatch(context.Request.Path, @"/api/\S*") && !Regex.IsMatch(context.Request.Path, @"/api/Test/\S*"))
                {
                    LogHelper.Info(new LogContent(ip, GlobalString.UserName, context.Request.Path, (string)context.Items["Message"], browserName + ' ' + ver, responseTimeForCompleteRequest.ToString()));
                }

                context.Response.Headers[RESPONSE_HEADER_RESPONSE_TIME] = responseTimeForCompleteRequest.ToString();
                return Task.CompletedTask;
            });
            // Call the next delegate/middleware in the pipeline   
            return this._next(context);
        }
    }
}
